package com.doge.calcalbum.business.vip.widgets

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.viewpager.widget.ViewPager
import com.doge.calcalbum.R
import com.doge.calcalbum.utils.dp

class IndicatorView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {
    private val dotSize = dp(6)
    private val spacing = dp(4)
    private val dotLayoutParam by lazy { MarginLayoutParams(dotSize, dotSize) }
    private val spacingLayoutParam by lazy { MarginLayoutParams(spacing * 2, dotSize) }
    private var pager: ViewPager? = null
    private val dotViews = mutableListOf<View>()

    private val listener = object : ViewPager.SimpleOnPageChangeListener() {
        override fun onPageSelected(position: Int) {
            update(position)
        }
    }

    fun set(count: Int) = initial(count)


    private fun createSpacing(): View {
        return View(context).apply { layoutParams = spacingLayoutParam }
    }

    private fun createDot(): View {
        return View(context).apply { layoutParams = dotLayoutParam }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        pager?.removeOnPageChangeListener(listener)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(dotSize, MeasureSpec.EXACTLY))
    }


    private fun initial(count: Int) {
        dotViews.clear()
        removeAllViewsInLayout()
        for (i in 0 until count) {
            val item = createDot()
            dotViews.add(item)
            addView(item)
            addView(createSpacing())
        }
        update(0)

        visibility = if (count <= 1) View.GONE else View.VISIBLE
    }

    fun attach(viewPager: ViewPager) {
        pager?.removeOnPageChangeListener(listener)
        viewPager.addOnPageChangeListener(listener)
        pager = viewPager
    }

    private fun update(selected: Int) {
        val dotCount = dotViews.size
        if (dotCount > 0) {
            val realSelected = selected % dotCount
            dotViews.forEachIndexed { index, view ->
                view.setBackgroundResource(
                    if (index == realSelected) R.drawable.shape_66ffffff_5 else R.drawable.shape_ffffff_oval
                )
                view.layoutParams = view.layoutParams.apply {
                    width = if (index == realSelected) (dotSize * 2.5f).toInt() else dotSize
                    height = dotSize
                }
            }
        }
    }
}